package jjn.round1;

import commons.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jjn
 * @since 2022-08-02 16:44
 */
public class LeetCode2326_SpiralMatrixIV {
    
    public int[][] spiralMatrix(int m, int n, ListNode head) {
        int[][] result = new int[m][n];
        int left = 0, right = n - 1;
        int top = 0, bottom = m - 1;
        List<Integer> data = getData(head);
        int finishedCount = 0;
        int cur = 0;
        while (left <= right) {
            while (top <= bottom) {
                // 纵坐标是top，从left -> right
                for (int i = left; i <= right; i++) {
                    result[top][i] = getDataFromList(data, cur++);
                    if (++finishedCount >= m * n) {
                        return result;
                    }
                }
                top++;
                // 横坐标是right，从top -> bottom
                for (int i = top; i <= bottom; i++) {
                    result[i][right] = getDataFromList(data, cur++);
                    if (++finishedCount >= m * n) {
                        return result;
                    }
                }
                right--;
                // 纵坐标是bottom，从right -> left
                for (int i = right; i >= left; i--) {
                    result[bottom][i] = getDataFromList(data, cur++);
                    if (++finishedCount >= m * n) {
                        return result;
                    }
                }
                bottom--;
                // 纵坐标是left，从bottom -> top
                for (int i = bottom; i >= top; i--) {
                    result[i][left] = getDataFromList(data, cur++);
                    if (++finishedCount >= m * n) {
                        return result;
                    }
                }
                left++;
            }
        }
        return result;
    }
    
    private Integer getDataFromList(List<Integer> data, int current) {
        int size = data.size();
        if (current >= size) {
            return -1;
        }
        return data.get(current);
    }
    
    private List<Integer> getData(ListNode head) {
        List<Integer> result = new ArrayList<>();
        while (head != null) {
            result.add(head.val);
            head = head.next;
        }
        return result;
    }
}
